<template>
	<view>
		<!-- 表单 -->
		<up-form :model="form" :borderBottom="true" ref="uFormRef" labelWidth="auto" style="padding: 0 20rpx;
				        background-color: #ffffff;">
			<view style="display: flex;align-items: center;">

				<!-- 转换 调出仓和调入仓 -->
				<text @click="swapWarehouses" class="custom-icon custom-icon-tiaohuan"
					style="font-size: 48rpx;padding: 0 20rpx;color: #4e77cf;"></text>
				<view style="flex:1;margin-left:20rpx">
					<up-form-item :borderBottom="true" label="调出仓" prop="transferOutWarehouse"
						required>
						<up-picker-data v-model="form.transferOutWarehouse"
							:inputProps="{inputAlign:'right',border:'none'}"
							:closeOnClickOverlay="true" :options="warehouseDict" labelKey="label"
							valueKey="value" hasInput style="width: 100%;"></up-picker-data>
						<template #right>
							<up-icon name="arrow-right"></up-icon>
						</template>
					</up-form-item>
					<up-form-item label="调入仓" prop="transferInWarehouse" :borderBottom="true"
						required>
						<up-picker-data v-model="form.transferInWarehouse"
							:inputProps="{inputAlign:'right',border:'none'}"
							:options="warehouseDict" :closeOnClickOverlay="true" labelKey="label"
							valueKey="value" hasInput style="width: 100%;"></up-picker-data>
						<template #right>
							<up-icon name="arrow-right"></up-icon>
						</template>
					</up-form-item>
				</view>
			</view>

			<!-- 填写更多 -->
			<view v-show="fillMoreShow">
				<up-form-item label="经办人" prop="handler" :borderBottom="true">
					<up-picker-data v-model="form.handler"
						:inputProps="{inputAlign:'right',border:'none',placeholder:'不填写默认为当前账号'}"
						:options="userDict" :closeOnClickOverlay="true" labelKey="label"
						valueKey="value" hasInput style="width: 100%;"></up-picker-data>
					<template #right>
						<up-icon name="arrow-right"></up-icon>
					</template>
				</up-form-item>
			</view>
			<view @click="fillMoreShow = !fillMoreShow" style="display: flex;
						 justify-content: center;
						 padding: 30rpx 0;">
				<up-icon labelPos="left" :label="fillMoreShow?'收起更多':'填写更多'"
					:name="fillMoreShow?'arrow-up':'arrow-down'" class="right"></up-icon>
			</view>
		</up-form>

		<!-- 加商品 -->
		<!-- <view class="bottom-box" id="bottom-box">
			<view style="padding: 20rpx;">
				<up-button type="primary" @click="toProductPage">添加商品</up-button>
			</view>
		</view> -->
		<drag-button :isDock="true" :existTabBar="true" :initPaddingBottom="300" text="添加商品"
			@btnClick="toProductPage" style="padding: 20rpx;" />
		
		<!-- 购物车列表 -->
		<view>
			<view style="font-size: 28rpx;
					     font-weight: 300;
					     background-color: #e3e8fb;
					     padding: 8rpx 20rpx;
					     display: flex;
					     justify-content: space-between;">
				<view>
					商品({{carList.length}})
				</view>
				<view>
					数量
				</view>
			</view>
			<view>
				<up-empty v-if="carList.length === 0" mode="data" icon="data"></up-empty>
				<up-swipe-action v-else>
					<up-swipe-action-item v-for="(item,index) in carList" @click="swipeClick"
						:name="index" :options="options">
						<view style="background-color: #ffffff;">
							<view style="display: flex;
										 padding: 20rpx 20rpx 0 20rpx;
										 justify-content: space-between;">
								<view>
									<!-- 商品名称 -->
									<view style="font-size: 24rpx;">
										<text style="color: #3c9cff;
													 padding: 4rpx 16rpx;
													 background-color: #edf0f9;">
											{{index+1}}
										</text>
										<text style="font-weight: bold;
													 font-size: 30rpx;
													 margin-left: 10rpx;">
											{{item.pname}}
										</text>
									</view>
									<!-- 库存 -->
									<view style="font-size: 24rpx;padding: 6rpx 0;">
										<text>[注]{{item.formulatext}}</text>
									</view>
								</view>
								<!-- 数量 -->
								<view style="font-weight: bold;font-size: 30rpx;">
									{{item.quantity}}{{item.selectedUnit}}
								</view>
							</view>
						</view>
					</up-swipe-action-item>
				</up-swipe-action>

			</view>
		</view>

		<!-- 占位置 -->
		<view :style="{height:paddingBottom+'px'}">
		</view>
		<view id="bottom-box" style="background-color: #ffffff;
					 position: fixed;
					 bottom: 0;
					 left: 0;
					 width: 100%;
					 z-index: 998;
					 box-sizing: content-box;
					 border-top: 1px solid #dedede;
					 padding-bottom: env(safe-area-inset-bottom);">
			<view style="padding: 20rpx;">
				<up-button type="primary" @click="submitClick">提交</up-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, watch, defineExpose, nextTick, computed } from 'vue'
	import { onReady, onLoad } from "@dcloudio/uni-app"
	import { useStore } from "vuex";

	const store = useStore();
	const app = getApp()

	// swipe滑动按钮
	const options = ref([{
		text: '删除',
		style: {
			backgroundColor: '#f56c6c'
		}
	}]);
	// 开关_表单展示更多  
	const fillMoreShow = ref(false);
	// 表单_数据
	const form = ref({
		transferOutWarehouse: null, // 调出仓
		transferInWarehouse: null, // 调入仓
		handler: null // 经办人
	})
	// 表单_引用
	const uFormRef = ref(null);
	// 表单_校验规则
	const rules = ref({
		transferOutWarehouse: [{
			required: true,
			type: 'number',
			message: '请选择调出仓',
			trigger: ['change', 'blur'],
		}],
		transferInWarehouse: [{
			required: true,
			type: 'number',
			message: '请选择调入仓',
			trigger: ['change', 'blur'],
		}]
	})
	// 页面布局相关变量
	const paddingBottom = ref(0)
	// picker
	const warehouseDict = ref([])
	const userDict = ref([])
	// 购物车
	const carList = ref([
		/*{
				pid: 1,
				pname: "小棕瓶",
				quantity:0,
				selectedUnit:'箱'
			}*/
	])

	onReady(async () => {
		// 如果需要兼容微信小程序，最好通过setRules方法设置rules规则
		uFormRef.value.setRules(rules.value)
		uni.createSelectorQuery().select('#bottom-box').boundingClientRect(b_data => {
			paddingBottom.value = b_data.height
		}).exec()
	})
	onLoad(async () => {
		const res = await app.globalData.http.get("/warehouse/dict")
		warehouseDict.value = res.data
		const userDictRes = await app.globalData.http.get("/sysUser/dict")
		userDict.value = userDictRes.data
	})
	// 监听_解决picker第一次选择后不触发form的表单校验的bug
	watch(() => form.value.transferOutWarehouse, (newVal, oldVal) => {
		if (oldVal == null) { // 只执行一次
			if (uFormRef.value) {
				uFormRef.value.validateField('transferOutWarehouse');
			}
		}
	});
	watch(() => form.value.transferInWarehouse, (newVal, oldVal) => {
		if (oldVal == null) { // 只执行一次
			if (uFormRef.value) {
				uFormRef.value.validateField('transferOutWarehouse');
			}
		}
	});

	// swipe滑动点击删除
	const swipeClick = (e) => {
		const index = e.name // 是第几条数据
		const operator = options.value[e.index].text
		if (operator === "删除") {
			carList.value.splice(index, 1)
		}
	}

	// 转换调入仓和调出仓
	const swapWarehouses = () => {
		const temp = form.value.transferOutWarehouse;
		form.value.transferOutWarehouse = form.value.transferInWarehouse;
		form.value.transferInWarehouse = temp;
	}

	// 去添加商品页
	const toProductPage = () => {
		if(form.value.transferOutWarehouse==null) {
			uni.showModal({
				showCancel: false,
				title: '请先选择调出仓库，再去添加商品!'
			})
			return 
		}
		uni.navigateTo({
			url: `/pagesTransfer/addProduct?id=${form.value.transferOutWarehouse}`
		})
	}

	// 添加商品到购物车
	const addProduct = (product) => {
		console.log(product)
		carList.value.push(product)
	}

	// 提交调拨单
	const submitClick = async () => {
		uFormRef.value.validate().then(async (valid) => {
			if (valid) {
				if (carList.value.length === 0) {
					app.globalData.modal.msgError("你还未添加任何商品")
					return
				}
				if (form.value.transferOutWarehouse === form.value
					.transferInWarehouse) {
					app.globalData.modal.msgError("调出仓与调入仓不能相同")
					return
				}
				const param = {
					whoutid: form.value.transferOutWarehouse,
					whinid: form.value.transferInWarehouse,
					owner: form.value.handler ? form.value.handler : store
						.state.user.userId,
					list: carList.value.map(item => ({
						pid: item.pid,
						number: item.quantity,
						unit: item.selectedUnit
					})),
				}
				const res = await app.globalData.http.post("/move/create", param)
				if (res.code == 200) {
					uni.showModal({
						showCancel: false,
						title: `创建订单成功!`,
						success: function(res) {
							if (res.confirm) {
								let pages = getCurrentPages()
								let prevPage = pages[pages.length -2]; //上一页页面实例
								prevPage._.exposed.initData()
								uni.navigateBack()
							}
						}
					})
				}
			}
		}).catch(() => {
			// 处理验证错误  
		});

	}
	// 一定要放在最后，不然会报错
	defineExpose({
		addProduct,
	})
</script>

<style>

</style>